const app = getApp()
const {throttle} = require('../../../utils/throttle')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    FjLoginLog: '',
    editId: '',
    editCate: '',
    // 类型
    typesFirstList: [], 
    typeFirstIdx: '',
    typesSecondList:[],
    typeSecondIdx: '',
    typesThirdList:[],
    typeThirdIdx: '',
    placeholder: '请选择',
    _level: '',
    // 回收量
    amount: '0',
    max_amount: '',
    min_amount: '',
    money: '0',
    min_money: '',
    max_money: '',
    // 提醒方式
    appChecked: true,
    weChatChecked: true,
    msgChecked: true,
    aiChecked: false,
    manChecked: false,
    keyworldList: [], // 关键词列表
    keyworld: '' // 关键词
  },

  // 点击类别框
  onClick(e){
    // 设置三角
    const { typesFirstList, typeFirstIdx, typesSecondList, typeSecondIdx, typesThirdList } = this.data
    const {_level} = e.target.dataset
    if(_level === '1'){
      if(!typesFirstList.length){
        return
      }
    } else if (_level === '2'){
      if(typeFirstIdx === '') {
        return
      } else if(!typesSecondList.length){
        return
      }
    } else {
      if(typeSecondIdx === '') {
        return
      } else if(!typesThirdList.length){
        return
      }
    }
    this.setData({
      _level: _level === this.data._level ? '' : _level
    })
  },

  // 类型确定
  bindChange(e){
    const { _level } = e.target.dataset
    const { value } = e.detail
    switch(_level){
      case '1':
        const { typesFirstList } = this.data
        this.setData({
          _level: '',
          typeFirstIdx: value,
          typesSecondList: typesFirstList[value] ? typesFirstList[value].children : [],
          typeSecondIdx: '',
          typesThirdList:[],
          typeThirdIdx: ''
        })
      break;  
      case '2':
        const { typesSecondList } = this.data
        this.setData({
          _level: '',
          typeSecondIdx: value,
          typesThirdList: typesSecondList[value] ? typesSecondList[value].children : [],
          typeThirdIdx: ''
        })
      break;
      case '3':
        this.setData({
          _level: '',
          typeThirdIdx: value
        })
      break;
      default: 
        this.setData({
          _level: '',
          typeFirstIdx: '',
          typeSecondIdx: '',
          typeThirdIdx: ''
        })
      break;
    }
  },

  bindcancel(){
    this.setData({
      _level: ''
    })
  },

  // 回收量,回收金额事件
  radioChange(e){
    this.setData({
      amount: e.detail.value,
    })
    if(e.detail.value == 0){
      this.setData({
        min_amount: '',
        max_amount: ''
      })
    }
  },
  radioChangeMoney(e){
    this.setData({
      money: e.detail.value
    })
    if(e.detail.value == 0){
      this.setData({
        min_money: '',
        max_money: ''
      })
    }
  },
  setAmount(e){
    const {_type} = e.target.dataset
    switch(_type){
      case 'min_amount':
        this.setData({
          min_amount: e.detail.value
        })
        break;
      case 'max_amount':
        this.setData({
          max_amount: e.detail.value
        })
        break;
      case 'min_money':
        this.setData({
          min_money: e.detail.value
        })
        break;
      case 'max_money':
        this.setData({
          max_money: e.detail.value
        })
        break;
    }
  },

  // 提醒方式
  switchChange(e){
    const obj = {}
    obj[`${e.target.dataset.type}Checked`] = e.detail.value
    this.setData({...this.data, ...obj})
  },

  throttle(){},
  sure(){
    this.throttle()
  },
  // 确认提交
  save(){
    const v = this.validate()
    if(!v) return
    // 判断是否有微信服务通知，调起服务通知授权
    if(!this.data.weChatChecked){
      this.alreadyAddValidate()
      return
    }
    this.subscribe()
  },
  // 校验
  validate(){
    if(this.data.typeFirstIdx === ''){
      wx.showToast({
        title: '请选择物资类型',
        icon: 'none'
      })
      return false
    } else if (this.data.typesSecondList.length && this.data.typeSecondIdx == ''){
      wx.showToast({
        title: '请选择物资类型',
        icon: 'none'
      })
      return false
    } else if (this.data.typesThirdList.length && this.data.typeThirdIdx == '') {
      wx.showToast({
        title: '请选择物资类型',
        icon: 'none'
      })
      return false
    }
    const { amount, min_amount, max_amount, money, min_money, max_money } = this.data
    if(amount === '1'){
      if(min_amount === ''){
        wx.showToast({
          title: '请输入最小回收量',
          icon: 'none'
        })
        return false
      } else if (max_amount === ''){
        wx.showToast({
          title: '请输入最大回收量',
          icon: 'none'
        })
        return false
      } else if (max_amount == 0){
        wx.showToast({
          title: '最大回收量须大于0',
          icon: 'none'
        })
        return false
      } else if ((min_amount * 1) > (max_amount * 1)){
        wx.showToast({
          title: '最小回收量须小于最大回收量',
          icon: 'none'
        })
        return false
      }
    }
    if(money === '1'){
      if(min_money === ''){
        wx.showToast({
          title: '请输入最小回收金额',
          icon: 'none'
        })
        return false
      } else if (max_money === ''){
        wx.showToast({
          title: '请输入最大回收金额',
          icon: 'none'
        })
        return false
      } else if (max_money == 0){
        wx.showToast({
          title: '最大回收金额须大于0',
          icon: 'none'
        })
        return false
      } else if ((min_money * 1) > (max_money * 1)){
        wx.showToast({
          title: '最小回收金额须小于最大回收金额',
          icon: 'none'
        })
        return false
      }
    }
    return true
  },
  // 判断是否添加过
  alreadyAddValidate(){
    const _this = this
    let last_cate = this.data.typesFirstList[this.data.typeFirstIdx]['num_id']
    if (this.data.typesSecondList.length) {
      last_cate = this.data.typesSecondList[this.data.typeSecondIdx]['num_id']
    }
    if(this.data.typesThirdList.length){
      last_cate = this.data.typesThirdList[this.data.typeThirdIdx]['num_id']
    }

    // 如果是修改并且物资类别未改变，则不用校验
    if((last_cate * 1) !== (this.data.editCate * 1)){
      wx.request({
        url: app.data.api_url2+"v/sign_cate_check/",
        header: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: {
          user_id: this.data.FjLoginLog.UID,
          'cate': last_cate
        },
        method: 'POST',
        success: function(res) {
          if (res.statusCode == 200) {
            if(res.data.code == 200){
              if(res.data.data.is_check == 1){
                wx.showToast({
                  title: '请勿重复添加类型',
                  icon: 'none'
                })
                return false
              }
              _this.add()
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        }
      })
      return 
    }
    _this.add()
  },
  // 添加
  add(){
    const params = this.getparams()
    wx.request({
      url: app.data.api_url2+"v/vip_cate_set/",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: params,
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 200){
            wx.showToast({
              title: '操作成功',
              icon: 'none'
            })
            setTimeout(()=>{
              wx.navigateBack()
            }, 500)
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
    })
  },
  // 设置参数
  getparams(){
    // 分类数组
    let cate_ids = []
    if(this.data.typesFirstList.length){
      cate_ids[0] = this.data.typesFirstList[this.data.typeFirstIdx]['num_id']
    } 
    if (this.data.typesSecondList.length) {
      cate_ids[1] = this.data.typesSecondList[this.data.typeSecondIdx]['num_id']
    }
    if(this.data.typesThirdList.length){
      cate_ids[2] = this.data.typesThirdList[this.data.typeThirdIdx]['num_id']
    }
    const { appChecked, weChatChecked, msgChecked, aiChecked, manChecked } = this.data
    // 提醒方式数组
    const arr = Array.from(
      [appChecked, weChatChecked, msgChecked, aiChecked, manChecked], 
      (item,index) => item && index + 1
    )
    const alarm_method = arr.filter(item => item)

    let params = {
      id: this.data.editId,
      user_id: this.data.FjLoginLog.UID,
      cate_ids,
      key_words: this.data.keyworldList.join(','),
      alarm_method
    }
    // 回收量
    if(this.data.amount === '1'){
      params.min_amount = this.data.min_amount
      params.max_amount = this.data.max_amount
    }
    // 回收金额
    if(this.data.money === '1'){
      params.min_money = this.data.min_money
      params.max_money = this.data.max_money
    }

    return params
  },
  // 服务消息通知授权
  /**
   * 当开启微信服务通知的时候判断是否永久授权
        1. 若永久授权并且拒绝，则判断总开关是否关闭，若关闭，则引导开启，并且设置消息接收
        2. 若永久授权并且通过，不进行任何判断
        3. 若未进行永久授权，则判断总开关收否关闭，若关闭，则引导开启，然后继续弹窗
   */
  subscribe(){
    const _this = this
    wx.getSetting({
      withSubscriptions: true,
      success (r) {
        const {mainSwitch, itemSettings} = r.subscriptionsSetting
        if (itemSettings && itemSettings['TitWyia1OaPHEvk3tnoW1AQsn1Wib9ZewynqprgcEEQ']) {
          if(itemSettings['TitWyia1OaPHEvk3tnoW1AQsn1Wib9ZewynqprgcEEQ']==='reject'){
              _this.openSetting()
          } else {
            if(!mainSwitch){ 
              _this.openSetting()
              return
            }
            _this.alreadyAddValidate()
          }
        } else {
          if(!mainSwitch){ 
            _this.openSetting()
            return
          }
          wx.requestSubscribeMessage({
            tmplIds: ['TitWyia1OaPHEvk3tnoW1AQsn1Wib9ZewynqprgcEEQ'],
            success () { 
              // 操作成功之后再次获取判断有无永久授权
              wx.getSetting({
                withSubscriptions: true,
                success (r) {
                  const {itemSettings} = r.subscriptionsSetting
                  console.log(itemSettings, 'ss111')
                  if (itemSettings && itemSettings['TitWyia1OaPHEvk3tnoW1AQsn1Wib9ZewynqprgcEEQ']) {
                    _this.setIsAuthShort(1)
                  } else {
                    _this.setIsAuthShort(0)
                  }
                }
              })
            },
            fail(){
              wx.showToast({
                title: '授权信息失败',
                icon: 'none'
              })
            }
          })          
        }
      }
    })
  },
  
  // 打开订阅消息
  openSetting(){
    wx.showModal({
      title: '提示',
      content: '检测到您没有开启订阅消息的权限，是否去设置？',
      success: function (sm) {
        if (sm.confirm) {         
            wx.openSetting()
          } else if (sm.cancel) { 
            wx.showToast({
              title: '您没有同意授权订阅消息，订阅失败',
              icon: 'none'
            }); 
          }
        }
      })
  },

  // 设置红点状态
  setIsAuthShort(sts){
    const _this = this
    console.log(sts, 'sts', _this.data.FjLoginLog.UID)
    wx.request({
      url: app.data.api_url2+"v/vip_mini_alarm_set/",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        user_id: _this.data.FjLoginLog.UID,
        sts: sts, // 0展示红点，1不展示红点'
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          _this.alreadyAddValidate()
        }
      }
    })
  },
  // 清除
  cancel(){
    this.setData({
      typeFirstIdx: '',
      typeSecondIdx: '',
      typeThirdIdx: '',
      amount: '0',
      max_amount: '',
      min_amount: '',
      money: '0',
      min_money: '',
      max_money: '',
      appChecked: true,
      weChatChecked: true,
      msgChecked: true,
      aiChecked: false,
      manChecked: false,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.throttle = throttle(this.save, 2000)
    this.getTypes()
    if(options._id){
      this.setData({
        editId: options._id,
      })
    }
  },
  onShow() {
    this.setData({
      FjLoginLog : wx.getStorageSync('FjLoginLog')
    })
  },
  // 获取类别
  getTypes(){
    const _this = this
    wx.request({
      url: app.data.api_url2+"v/sign_cate_select/",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 200){
            _this.setData({
              typesFirstList: res.data.data
            })
            if(_this.data.editId){
              _this.getDetails()
            }
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
    })
  },
  // 若是编辑调取详情
  getDetails(){
    const _this = this
    wx.request({
      url: app.data.api_url2+"v/sign_cate_detail/",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      data: {
        'id': _this.data.editId
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode == 200) {
          if(res.data.code == 200){
            _this.setGoodData(res.data.data)
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      }
    })
  },
  // 赋值
  setGoodData(info){
    // 设置类别
    const { typesFirstList } = this.data
    const typeFirstIdx = typesFirstList.findIndex(item => item.num_id == info.c1)
    let typesSecondList = []
    let typeSecondIdx = ''
    let typesThirdList = []
    let typeThirdIdx = ''
    if(info.c2){
      typesSecondList = typesFirstList[typeFirstIdx].children
      typeSecondIdx = typesSecondList.findIndex(item => item.num_id == info.c2)
    }
    if(info.c3){
      typesThirdList = typesSecondList[typeSecondIdx].children
      typeThirdIdx = typesThirdList.findIndex(item => item.num_id == info.c3)
    }
    
    // 设置回收量，回收金额
    let amount = '0'
    let max_amount = ''
    let min_amount = ''
    let money = '0'
    let max_money = ''
    let min_money = ''

    if(info.max_amount){
      amount = '1'
      max_amount = info.max_amount
      min_amount = info.min_amount
    }
    if(info.max_money){
      money = '1'
      max_money = info.max_money
      min_money = info.min_money
    }

    // 设置提醒方式
    let appChecked = info.alarm_method.includes('1')
    let weChatChecked = info.alarm_method.includes('2')
    let msgChecked = info.alarm_method.includes('3')
    let aiChecked = info.alarm_method.includes('4')
    let manChecked = info.alarm_method.includes('5')
    // 关键词
    let keyworldList = []
    if(info.key_words && info.key_words.length > 0) {
      keyworldList = info.key_words.split(',')
    }

    this.setData({
      typeFirstIdx,
      typesSecondList,
      typeSecondIdx,
      typesThirdList,
      typeThirdIdx,
      amount,
      max_amount,
      min_amount,
      money,
      max_money,
      min_money,
      appChecked,
      weChatChecked,
      msgChecked,
      aiChecked,
      manChecked,
      editCate: info.cate,
      keyworldList
    })
  },
  // 输入关键字
  setKeyword(e) {
    this.setData({
      keyworld: e.detail.value
    })
  },
  // 添加关键词
  handleAddKeyword() {
    if(!this.data.keyworld) {
      return
    }
    this.data.keyworldList.push(this.data.keyworld)
    this.setData({
      keyworld: '',
      keyworldList: this.data.keyworldList
    })
  },
  // 删除关键词
  handleDeleteKeyword(e) {
    let index = e.currentTarget.dataset['index']
    this.data.keyworldList.splice(index, 1)
    this.setData({
      keyworldList: this.data.keyworldList
    })
  },
})